<template>
  <div style="overflow-y: hidden">
    <div v-if="route.query.singleCode" class="op-btns">
      <div class="left">
        <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" inline label-width="90px">
          <px-form-item label="时间" prop="handoverTime" style="width: 500px">
            <!-- <px-date-picker
              v-model="queryParams.handoverStartTime"
              clearable
              type="datetime"
              :editable="false"
              format="YYYY/MM/DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择开始时间"
            /> -->
            <px-date-picker
              v-model="queryParams.handoverTime"
              clearable
              type="daterange"
              range-separator="至"
              start-placeholder="请选择开始时间"
              end-placeholder="请选择结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </px-form-item>
          <!-- <px-form-item label="开始时间" prop="startTime">
            <px-date-picker
              v-model="queryParams.handoverStartTime"
              clearable
              type="datetime"
              :editable="false"
              format="YYYY/MM/DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择开始时间"
            />
          </px-form-item>
          <px-form-item label="结束时间" prop="endTime">
            <px-date-picker
              v-model="queryParams.handoverEndTime"
              clearable
              type="datetime"
              :editable="false"
              format="YYYY/MM/DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="new Date(2000, 1, 1, 23, 59, 59)"
              placeholder="请选择结束时间"
            />
          </px-form-item> -->
          <px-form-item class="option-item">
            <px-button type="primary" @click="searchAction">查询</px-button>
            <!-- <px-button @click="resetQuery">重置</px-button> -->
          </px-form-item>
        </px-form>
      </div>
      <!-- <div class="center" style="max-width: 200px">
        <px-button type="primary" plain @click="exportAction">下载</px-button>
        <px-button type="primary" plain @click="printAction">打印</px-button>
      </div> -->
      <div class="right">
        <px-button v-has="'HANDOVER_DETAIL_SIGN_RECORD'" type="primary" plain @click="signListAction">签核记录</px-button>
      </div>

      <!-- <px-button v-if="route.query.id" type="danger" @click="deleteAction">删除</px-button> -->
    </div>
    <div
      class="content"
      style="position: relative; height: calc(100vh - 160px); overflow-y: hidden"
      :style="{ height: route.query.singleCode ? 'calc(100vh - 160px)' : 'calc(100vh - 80px)' }"
    >
      <div
        v-if="
          route.query.singleCode ||
          ((route.query.singleCode || writeSingleCode) && (approvalFlow?.handovers || approvalFlow?.handoverSigns || approvalFlow?.successors))
        "
        class="left"
      >
        <div v-if="route.query.singleCode" class="record-list" :class="{ collapses: collapse }" style="height: calc(100% - 18px)">
          <div class="title">交接簿列表</div>
          <div
            class="record-content"
            :class="{
              'no-border-right':
                !collapse &&
                (route.query.singleCode || writeSingleCode) &&
                (approvalFlow?.handovers || approvalFlow?.handoverSigns || approvalFlow?.successors)
            }"
          >
            <px-table v-loading="loading" :data="tableData" height="100%" border style="width: 100%" :show-overflow-tooltip="true">
              <template #empty>
                <px-empty />
              </template>
              <px-table-column width="40" align="center" :show-overflow-tooltip="false">
                <template #default="scope">
                  <px-radio v-model="selectedRowIndex" :label="scope.$index" @change="selectRowChange(scope.row)" />
                </template>
              </px-table-column>
              <!-- <px-table-column prop="reportName" label="文档名称" width="120" />
              <px-table-column prop="handoverPerson" label="交班人" min-width="80">
                <template #default="scope">
                  <UserName :userId="scope.row.handoverPerson" :userList="userList" />
                </template>
              </px-table-column>
              <px-table-column prop="successorPerson" label="接班人" min-width="80">
                <template #default="scope">
                  <UserName :userId="scope.row.successorPerson" :userList="userList" />
                </template>
              </px-table-column> -->
              <px-table-column prop="handoverWorkShift" label="值班时间" min-width="100" />
              <px-table-column prop="handoverTime" label="值班日期" min-width="100">
                <template #default="scope">{{ dayjs(scope.row.handoverTime).format("YYYY-MM-DD") }}</template>
              </px-table-column>
            </px-table>
            <div style="padding-top: 10px; padding-left: 15px">
              <px-pagination
                v-if="total > 0"
                v-model:current-page="queryParams.pageNum"
                v-model:page-size="queryParams.pageSize"
                small
                layout="total, sizes, prev, pager, next"
                :total="total"
                @current-change="queryTable"
                @size-change="queryTable"
              />
            </div>
          </div>
          <div v-if="route.query.singleCode" class="collopse-btn" :class="{ collapse: collapse }" @click="switchCollapse">
            <px-icon><ArrowLeft /></px-icon>
          </div>
        </div>
        <div
          v-if="(route.query.singleCode || writeSingleCode) && (approvalFlow?.handovers || approvalFlow?.handoverSigns || approvalFlow?.successors)"
          class="sign-flow"
          :class="{ collapses: collapse }"
        >
          <div v-if="!collapse" class="title">交接班审批记录</div>
          <div class="sign-flow-content">
            <px-timeline class="sign-line">
              <px-timeline-item :icon="approvalFlow?.handovers?.isOperation ? userGroupActive : userGroup" timestamp="">
                <div class="left">
                  <div class="info">
                    <ApprovalStatus :status="getLatestItem(approvalFlow?.handovers?.dataList).recordStatus" />
                    <div class="type">交班人</div>
                  </div>
                  <div class="time">{{ getLatestItem(approvalFlow?.handovers?.dataList).submitTime }}</div>
                </div>
                <div class="right">
                  <div v-for="(item, index) in approvalFlow?.handovers?.dataList" :key="index" :class="getOpreateClass(item)">
                    <UserName :userList="userList" :userId="item.taskPerson" />
                  </div>
                </div>
              </px-timeline-item>
              <px-timeline-item
                v-if="approvalFlow?.handoverSigns"
                :icon="approvalFlow?.handoverSigns?.isOperation ? userGroupActive : userGroup"
                timestamp=""
              >
                <div class="left">
                  <div class="info">
                    <ApprovalStatus type="SIGN" :status="getLatestItem(approvalFlow?.handoverSigns?.dataList).recordStatus" />
                    <div class="type">签核人</div>
                  </div>
                  <div class="time">{{ getLatestItem(approvalFlow?.handoverSigns?.dataList).submitTime }}</div>
                </div>
                <div class="right">
                  <div v-for="(item, index) in approvalFlow?.handoverSigns?.dataList" :key="index" :class="getOpreateClass(item)">
                    <UserName :userList="userList" :userId="item.taskPerson" />
                  </div>
                </div>
              </px-timeline-item>
              <px-timeline-item :icon="approvalFlow?.successors?.isOperation ? userGroupActive : userGroup" timestamp="">
                <div class="left">
                  <div class="info">
                    <ApprovalStatus :status="getLatestItem(approvalFlow?.successors?.dataList).recordStatus" />
                    <div class="type">接班人</div>
                  </div>
                  <div class="time">{{ getLatestItem(approvalFlow?.successors?.dataList).submitTime }}</div>
                </div>
                <div class="right">
                  <div v-for="(item, index) in approvalFlow?.successors?.dataList" :key="index" :class="getOpreateClass(item)">
                    <UserName :userList="userList" :userId="item.taskPerson" />
                  </div>
                </div>
              </px-timeline-item>
              <px-timeline-item
                v-if="approvalFlow?.successorSigns"
                :icon="approvalFlow?.successorSigns?.isOperation ? userGroupActive : userGroup"
                timestamp=""
              >
                <div class="left">
                  <div class="info">
                    <ApprovalStatus type="SIGN" :status="getLatestItem(approvalFlow?.successorSigns?.dataList).recordStatus" />
                    <div class="type">签核人</div>
                  </div>
                  <div class="time">{{ getLatestItem(approvalFlow?.successorSigns?.dataList).submitTime }}</div>
                </div>
                <div class="right">
                  <div v-for="(item, index) in approvalFlow?.successorSigns?.dataList" :key="index" :class="getOpreateClass(item)">
                    <UserName :userList="userList" :userId="item.taskPerson" />
                  </div>
                </div>
              </px-timeline-item>
            </px-timeline>
          </div>
        </div>
      </div>

      <div
        class="frame"
        :class="{
          gas: dataDetail.className == 'GAS' || templateName.indexOf('气化科') != -1,
          water:
            dataDetail.className == 'WATER' ||
            templateName.indexOf('水科') != -1 ||
            dataDetail.className == 'MACHINE' ||
            templateName.indexOf('机械科') != -1
        }"
      >
        <iframe id="reportFrame" :src="templateUrl" width="100%" height="100%" frameborder="0" />
      </div>
    </div>

    <div class="op-btns footer-btns">
      <div class="left" />
      <div class="center">
        <px-button v-has="'HANDOVER_DETAIL_DOWNLOAD'" type="primary" plain @click="exportAction">下载</px-button>
        <px-button v-has="'HANDOVER_DETAIL_PRINT'" type="primary" plain @click="printAction">打印</px-button>
        <px-button v-if="!route.query.taskId && canCommit" v-has="'HANDOVER_DETAIL_SAVE'" type="primary" plain @click="saveAction">保存</px-button>
      </div>
      <div class="right">
        <px-button v-if="!route.query.taskId && canCommit" v-has="'HANDOVER_DETAIL_SUBMIT'" type="primary" @click="submitAction">提交</px-button>
      </div>
    </div>
    <px-dialog v-model="signRecordVisible" title="主办工程师签核记录" @close="closeDialog">
      <px-table v-loading="signLoading" :data="signList" height="500" border style="width: 100%" :show-overflow-tooltip="true">
        <template #empty>
          <px-empty />
        </template>
        <px-table-column prop="submitTime" label="时间" min-width="120" />
        <px-table-column prop="taskPerson" label="工程师" min-width="120">
          <template #default="scope">
            <UserName :userList="userList" :userId="scope.row.taskPerson" />
          </template>
        </px-table-column>
        <px-table-column prop="recordStatus" label="签核状态" min-width="80">
          <template #default="scope">
            <ApprovalStatus type="SIGN" :status="scope.row.recordStatus" />
          </template>
        </px-table-column>
        <px-table-column prop="recordMessage" label="问题描述" min-width="80" />
      </px-table>
    </px-dialog>
    <div v-if="route.query.taskId && approvalSwitch && taskOperationStatus == 'NO'" class="approval-float-btn" @click="switchApprovalAction">
      <px-icon><UserFilled /></px-icon>
      <div class="text">待处理!</div>
    </div>
    <div v-if="route.query.taskId && !approvalSwitch && taskOperationStatus == 'NO'" class="approval-content">
      <div class="header">
        <div class="title">交接班台账已提交，请确认</div>
        <px-icon @click="switchApprovalAction"><UserFilled /></px-icon>
      </div>
      <px-form ref="formRef" :model="formParams" label-width="0" label-position="right" :rules="formRules">
        <px-form-item label="" prop="message">
          <px-input v-model="formParams.message" type="textarea" rows="4" placeholder="添加评论" />
        </px-form-item>
      </px-form>
      <div class="footer">
        <div class="left"><px-button v-has="'HANDOVER_DETAIL_SIGN_REJECT'" type="danger" @click="approvalAction(1)">驳回</px-button></div>
        <div class="right"><px-button v-has="'HANDOVER_DETAIL_SIGN_APPROVE'" type="primary" @click="approvalAction(2)">确认</px-button></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  querySignList,
  handoverSubmit,
  handoverFlow,
  userlistPage,
  handoverConfirm,
  handoverSign,
  queryHandoverRecord,
  queryTaskInfo,
  queryCanCommit,
  queryHandoverData
} from "@/api/handover";
import { onMounted, reactive, toRefs, ref, unref, computed, nextTick } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { UserFilled, ArrowLeft } from "@px-ui/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { useRouterStoreHook } from "@/store/modules/router";
import { useNav } from "@/layout/hooks/useNav";
import ApprovalStatus from "../components/ApprovalStatus.vue";
import UserName from "../components/UserName.vue";

import userGroup from "@/assets/svg/usergroup_outline.svg?component";
import userGroupActive from "@/assets/svg/usergroup_filled.svg?component";
import { getToken } from "@/utils/auth";
import dayjs from "dayjs";

const routerStore = useRouterStoreHook();
defineOptions({
  name: "FULLSCREEN_TEMPLATE_DETAIL"
});
function removeURLParameter(url, parameter) {
  var urlparts = url.split("?");
  if (urlparts.length >= 2) {
    var prefix = encodeURIComponent(parameter) + "=";
    var pars = urlparts[1].split(/[&;]/g);
    for (var i = pars.length; i-- > 0; ) {
      // 如果参数是我们想要移除的，则移除它
      if (pars[i].lastIndexOf(prefix, 0) !== -1) {
        pars.splice(i, 1);
      }
    }
    // 重新组合URL
    url = urlparts[0] + "?" + pars.join("&");
    return url;
  } else {
    return url;
  }
}
const { username } = useNav();
const router = useRouter();
const route = useRoute();

const tableData = ref([]);
const loading = ref(false);
const total = ref(0);
const collapse = ref(true);
const writeSingleCode = ref();
const userList = ref([]);
const signRecordVisible = ref(false);
const signLoading = ref(false);
const signList = ref([]);
const canCommit = ref(false);
const templateName = ref("");
const dataDetail = reactive({
  className: ""
});
const switchCollapse = () => {
  collapse.value = !collapse.value;
};

const approvalFlow = ref({
  handovers: null,
  handoverSigns: null,
  successors: null,
  successorSigns: null
});
const approvalSwitch = ref(false);

const templateUrl = ref();
const formRef = ref();
const formParams = reactive({
  message: ""
});
// 获取当前月份第一天
const n_d = new Date();
const firstDayOfMonth = dayjs(new Date(n_d.getFullYear(), n_d.getMonth(), 1)).format("YYYY-MM-DD");
// 获取当前月份最后一天
const lastDayOfMonth = dayjs(new Date(n_d.getFullYear(), n_d.getMonth() + 1, 0)).format("YYYY-MM-DD");
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  className: routerStore.subject === "ALL" ? "" : routerStore.subject, // 先写死 后续再改
  handoverStartTime: "",
  handoverEndTime: "",
  handoverTime: [firstDayOfMonth, lastDayOfMonth]
});
const searchAction = () => {
  queryParams.pageNum = 1;
  queryTable();
};
const queryTable = async () => {
  try {
    loading.value = true;
    queryParams.handoverStartTime = queryParams?.handoverTime?.[0] || "";
    queryParams.handoverEndTime = queryParams?.handoverTime?.[1] || "";
    const res = await queryHandoverRecord(queryParams);
    collapse.value = true;
    tableData.value = res?.data || [];
    selectedRowIndex.value = -1;
    tableData.value.forEach((v, i) => {
      if (v.singleCode == route.query.singleCode) {
        selectedRowIndex.value = i;
      }
    });
    total.value = res?.total;
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};
const formRules = reactive({
  // message: [{ required: true, trigger: "blur", message: "Please input" }],
});
// 帆软的保存数据
const saveAction = () => {
  // if (!route.query.singleCode) {
  //   if (!writeSingleCode.value) {
  //     document.getElementById("reportFrame").contentWindow.postMessage("_g().verifyAndWriteReport()", "*");
  //   } else {
  //     PxMessage.info("数据已保存成功！");
  //     console.log("已保存");
  //   }
  // } else {
  //   document.getElementById("reportFrame").contentWindow.postMessage("_g().verifyAndWriteReport()", "*");
  // }
  document.getElementById("reportFrame").contentWindow.postMessage("_g().verifyAndWriteReport()", "*");
};
//调用接口提交
const submitAction = async () => {
  if (!route.query.singleCode && !writeSingleCode.value) {
    PxMessage.error("请先保存数据");
    return;
  }
  try {
    let params = {
      submitUserNo: JSON.parse(localStorage.getItem("userInfo")).userId,
      dataSingleCode: route.query.singleCode || writeSingleCode.value
    };
    let res = await handoverSubmit(params);
    PxMessage.success("提交成功");

    const path = "/fullScreen/handleover/detail";
    const query = {
      template: route.query.template || `${encodeURIComponent(encodeURIComponent(route.query.moduleName as string))}.cpt`,
      op: "write",
      singleCode: route.query.singleCode || writeSingleCode.value
    };
    const { href } = router.resolve({ path, query });
    window.location.replace(href);
    // queryHandoverFlow();
  } catch (error) {}
};
// importExcel_Clean清空导入
// importExcel_Append 增量导入
// importExcel_Cover 覆盖导入
const importAction = () => {
  document.getElementById("reportFrame").contentWindow.postMessage("_g().importExcel_Cover()", "*");
};
const exportAction = () => {
  document.getElementById("reportFrame").contentWindow.postMessage("_g().exportReportToExcel('simple')", "*");
};
// const deleteAction = () => {
//   PxMessageBox.confirm(`是否该条记录数据？`, "温馨提示", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//     draggable: true
//   })
//     .then(async () => {
//       await deleteReportRecord({ ids: [route.query.id] });
//       PxMessage.success("删除成功");
//       templateUrl.value = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=${route.query.template}&user=${username.value}&__pi__=false`;
//       localStorage.setItem("listen_report_record_delete", "true");
//       setTimeout(() => {
//         window.close();
//       }, 1500);
//     })
//     .catch(() => {});
//   //window.close()
// };
const printAction = () => {
  // let config = JSON.stringify({
  //   printUrl: `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report`,
  //   printType: 1,
  //   isPopUp: true,
  //   data: {
  //     reportlets:[{reportlet: `${route.query.template}`}]
  //   }
  // })
  // let config = JSON.stringify({ url: `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=${route.query.template}`, isPopUp: true });
  // document.getElementById("reportFrame").contentWindow.postMessage(`FR.doURLPDFPrint(${config})`, "*");
  document.getElementById("reportFrame").contentWindow.postMessage(`_g().noClientPrint(false,true)`, "*");
};
const signListAction = async () => {
  signRecordVisible.value = true;
  let res = await querySignList({ dataSingleCode: route.query.singleCode });
  signList.value = res;
};
const queryHandoverFlow = async singleCode => {
  if (!route.query.singleCode && !writeSingleCode.value) {
    return;
  }
  let res = await handoverFlow({ dataSingleCode: singleCode || route.query.singleCode || writeSingleCode.value });
  approvalFlow.value = res;
};

const getOpreateClass = item => {
  return item.operateStatus == "YES" && item.recordStatus != "REJECTED"
    ? "pass"
    : item.operateStatus == "YES" && item.recordStatus == "REJECTED"
      ? "reject"
      : "";
};

const getLatestItem = list => {
  if (!list || list?.length == 0) {
    return {};
  }
  let latestItem = list?.[0];
  list.forEach(item => {
    if (item.submitTime && new Date(item.submitTime).getTime() > new Date(latestItem.submitTime).getTime()) {
      latestItem = item;
    }
  });
  // let latestItem = list?.reduce((maxItem,current) => {
  //   return Math.max(new Date(maxItem.submitTime).getTime(), new Date(current.submitTime).getTime())
  // });
  return latestItem;
};

const selectedRowIndex = ref(-1);
const selectRowChange = row => {
  console.log("index:" + selectedRowIndex.value);
  // TODO 跳转当前url
  // const path = "/fullScreen/handleover/detail";
  // const query = {
  //   template: encodeURIComponent(encodeURIComponent("电科交接簿")) + ".cpt",
  //   op: "write",
  //   singleCode: row.singleCode,
  //   id: row.id
  // };
  router.replace({
    path: "/fullScreen/handleover/detail",
    query: {
      template: route.query.template || `${encodeURIComponent(encodeURIComponent(route.query.moduleName as string))}.cpt`,
      op: "write",
      singleCode: row.singleCode,
      id: row.id
    }
  });
  //判断水科
  if (
    (route.query.moduleName && (route.query.moduleName.indexOf("水科") != -1 || route.query.moduleName.indexOf("机械科") != -1)) ||
    templateName.value.indexOf("水科") != -1 ||
    templateName.value.indexOf("机械科") != -1
  ) {
    templateUrl.value = `${window.location.protocol}//${window.location.hostname}:8443/webroot/decision/view/report?viewlet=${route.query.template || `${encodeURIComponent(encodeURIComponent(route.query.moduleName as string))}.cpt`}&singleCode=${row.singleCode}&user=${username.value}&token=${getToken().accessToken}&ifpHost=${window.location.protocol}//${window.location.hostname}&facCode=${localStorage.getItem("facCode") || ""}`;
  } else {
    templateUrl.value = `${window.location.protocol}//${window.location.hostname}:8443/webroot/decision/view/report?viewlet=${route.query.template || `${encodeURIComponent(encodeURIComponent(route.query.moduleName as string))}.cpt`}&singleCode=${row.singleCode}&user=${username.value}&__pi__=false&facCode=${localStorage.getItem("facCode") || ""}`;
  }
  queryHandoverFlow(row.singleCode);
  getCanCommit();
  // const params = { path, query };
  // const { href } = router.resolve(params);
  // location.href = href;
};
const { VITE_FANRUAN_BASE_URL } = import.meta.env;

const closeDialog = () => {
  signRecordVisible.value = false;
};
const switchApprovalAction = () => {
  approvalSwitch.value = !approvalSwitch.value;
};
const approvalAction = async type => {
  // type 1: 驳回  2: 确认
  // handoverSignApproval, successorApproval, successorSignApproval
  let funcName = null;
  if (route.query.url == "SUBMIT") {
    funcName = handoverConfirm;
  }
  if (route.query.url == "SIGN") {
    funcName = handoverSign;
  }
  // if (route.query.url == "c") {
  //   funcName = successorSignApproval;
  // }
  if (funcName && route.query.taskId) {
    let params = {
      taskId: route.query.taskId,
      dataSingleCode: route.query.singleCode,
      submitUserNo: JSON.parse(localStorage.getItem("userInfo")).userId,
      confirm: type == 2 ? true : false,
      message: formParams.message
    };
    await funcName(params);
    PxMessage.success("签核提交成功");
    queryHandoverFlow();
    getTaskInfo();
  }
};
const getUserList = async () => {
  const res = await userlistPage({ pageSize: 2000 }); //ELECTRICTITY
  userList.value = res.map(item => ({ value: item.userId, label: item.username + "-" + item.realName, phone: item.phone, userId: item.userId }));
  // userList.value = await getEmployeeIdAndName();
  queryHandoverFlow();
};
const taskOperationStatus = ref("");
const getTaskInfo = async () => {
  if (route.query.taskId) {
    const res = await queryTaskInfo({ taskId: route.query.taskId }); //ELECTRICTITY
    taskOperationStatus.value = res.operateStatus;
  }
};

const getCanCommit = async () => {
  if (route.query.singleCode) {
    let userId = JSON.parse(localStorage.getItem("userInfo")).userId;
    const res: any = await queryCanCommit({ user: userId, singleCode: route.query.singleCode }); //ELECTRICTITY
    canCommit.value = res;
  } else {
    canCommit.value = true;
  }
  if (canCommit.value) {
    templateUrl.value = `${templateUrl.value}&op=write`;
  } else {
    if (templateName.value.indexOf("水科") != -1 || templateName.value.indexOf("机械科") != -1) {
      templateUrl.value = `${templateUrl.value}&op=view&token=${getToken().accessToken}`;
    }
  }
};

const getHandoverDetail = async () => {
  if (route.query.singleCode) {
    const res: any = await queryHandoverData({ singleCode: route.query.singleCode });
    dataDetail.className = res.className;
    queryParams.className = dataDetail.className;
    searchAction();
  } else {
    searchAction();
  }
};

onMounted(() => {
  let baseUrl = "";
  if (route.query.moduleName) {
    try {
      templateName.value = route.query.moduleName;
      baseUrl = `${window.location.protocol}//${window.location.hostname}:8443/webroot/decision/view/report?viewlet=${encodeURIComponent(encodeURIComponent(route.query.moduleName as string))}.cpt&user=${username.value}&__pi__=false&op=write&facCode=${localStorage.getItem("facCode") || ""}`;
    } catch (error) {
      console.log("error:" + error);
    }
  } else {
    templateName.value = decodeURIComponent(decodeURIComponent(route.query.template.split(".")[0]));
    baseUrl = `${window.location.protocol}//${window.location.hostname}:8443/webroot/decision/view/report?viewlet=${route.query.template}&user=${username.value}&__pi__=false&facCode=${localStorage.getItem("facCode") || ""}`;
  }
  if (route.query.singleCode) {
    baseUrl = `${baseUrl}&singleCode=${route.query.singleCode}`;
  } else {
    baseUrl = `${baseUrl}&userId=${JSON.parse(localStorage.getItem("userInfo")).userId}`;
  }
  if (
    (route.query.moduleName && (route.query.moduleName.indexOf("水科") != -1 || route.query.moduleName.indexOf("机械科") != -1)) ||
    templateName.value.indexOf("水科") != -1 ||
    templateName.value.indexOf("机械科") != -1
  ) {
    baseUrl = removeURLParameter(baseUrl, "__pi__");
    baseUrl = `${baseUrl}&token=${getToken().accessToken}&ifpHost=${window.location.protocol}//${window.location.hostname}`;
  }
  console.log("template name:" + templateName.value);
  templateUrl.value = baseUrl;
  getUserList();
  getTaskInfo();
  getCanCommit();
  getHandoverDetail();
  window.addEventListener("message", function (event) {
    console.log(event);
    let o = `${window.location.protocol}//${window.location.hostname}:8443`;
    if (event.origin !== o) return;
    let code = JSON.parse(event.data)?.singleCode;
    let jumpUrl = JSON.parse(event.data)?.jumpUrl;
    if (code) {
      writeSingleCode.value = code;
      if (templateUrl.value.indexOf("singleCode") == -1) {
        templateUrl.value = templateUrl.value + "&singleCode=" + code;
      }
    }
    if (jumpUrl) {
      window.open(jumpUrl, "_blank");
    }
  });
});
</script>
<style scoped lang="scss">
.template-content {
  width: 100%;
}

.content {
  display: flex;
  justify-content: center;
  padding: 10px 0;
  background: #f0f2f5;

  > div {
    &.left {
      display: flex;
      max-width: 730px;
      padding: 16px 12px;
      margin-left: 16px;
      background: #fff;
      box-shadow: 0 0 10px 0 rgb(0 0 0 / 10%);

      & .record-list {
        position: relative;
        width: 350px;
        // transition: width var(--px-transition-duration-fast) ease-in-out;
        .record-content {
          height: calc(100% - 30px);
          padding: 10px;
          padding-bottom: 48px;
          border: 1px solid #dcdcdc;

          &.no-border-right {
            border-right: 0;
          }
        }

        &.collapses {
          .record-content {
            border: none;
          }
        }
        // &.collapses {
        //   width: 0;
        // }

        .title {
          margin-bottom: 16px;
          font-size: 16px;
          font-weight: 600;
          color: #0e0f10;
          text-align: left;
        }

        .collopse-btn {
          position: absolute;
          top: 50%;
          right: 0;
          z-index: 800;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 24px;
          height: 24px;
          margin-top: -12px;
          margin-right: -24px;
          line-height: 24px;
          text-align: center;
          cursor: pointer;
          background: #cfe1ff;
          transition: right var(--px-transition-duration-fast) ease-in-out;

          &.collapse {
            right: 11px;
            visibility: visible;

            .px-icon {
              transform: rotate(180deg);
            }
          }
        }
      }

      & .sign-flow {
        position: relative;
        width: 380px;
        overflow: auto;
        // padding: 16px 12px;
        // margin-top: 16px;
        // margin-right: 16px;
        &.collapses {
          width: 0;
          overflow: hidden;
        }

        .sign-flow-content {
          height: calc(100% - 48px);
          padding: 10px 20px;
          border: 1px solid #dfdfdf;
        }

        .title {
          margin-bottom: 16px;
          font-size: 16px;
          font-weight: 600;
          color: #0e0f10;
          text-align: center;
        }

        .sign-line {
          padding: 16px;
          // padding-left: 175px;
          padding-left: 196px;
          font-size: 14px;

          .left {
            position: absolute;
            left: -175px;
            width: 175px;

            &.disable {
              .info {
                .type {
                  color: #aeaeae !important;
                }
              }
            }

            .info {
              position: relative;
              padding-right: 10px;
              overflow: hidden;

              .status {
                float: left;
              }

              .status-sign {
                float: left;
              }

              .type {
                right: 10px;
                float: right;
                width: 76px;
                font-weight: 600;
                color: rgb(0 0 0 / 80%);
                text-align: center;
              }
            }

            .time {
              padding-top: 4px;
              font-size: 12px;
              color: rgb(0 0 0 / 40%);
              text-align: left;
            }
          }

          .right {
            padding-left: 10px;

            &.disable {
              color: #aeaeae !important;
            }

            > div {
              padding-bottom: 4px;
            }

            .pass {
              font-weight: 600;
              color: #10b981;
            }

            .reject {
              font-weight: 600;
              color: #ef4444;
            }
          }
        }
      }
    }

    &.frame {
      flex: 1;
      min-width: 900px;
      max-width: 1000px;
      padding: 12px;
      margin-left: 16px;
      background: #fff;
      box-shadow: 0 0 10px 0 rgb(0 0 0 / 10%);

      &.gas {
        max-width: 1480px;
      }

      &.water {
        max-width: 1400px;
      }
    }
  }
}

.op-btns {
  display: flex;
  padding: 16px;
  margin: 5px 0;
  // box-shadow: 0 0 10px 0 rgb(0 0 0 / 10%);

  > div {
    flex: 1;

    &.right {
      text-align: right;
    }

    &.center {
      text-align: center;
    }
  }
}

.footer-btns {
  text-align: right;
}

.approval-float-btn {
  position: fixed;
  right: 20px;
  bottom: 100px;
  z-index: 800;
  width: 73px;
  height: 66px;
  font-size: 14px;
  color: #323333;
  // border: 1px solid #DCDCDC;
  text-align: center;
  cursor: pointer;
  background: #fff;
  border-radius: 6px;
  box-shadow:
    0 6px 30px 5px rgb(0 0 0 / 5%),
    0 16px 24px 2px rgb(0 0 0 / 4%),
    0 8px 10px -5px rgb(0 0 0 / 8%);

  .px-icon {
    padding-top: 14px;
    font-size: 22px;
    color: #3b82f6;
  }
}

.approval-content {
  position: fixed;
  right: 20px;
  bottom: 100px;
  z-index: 801;
  width: 335px;
  min-height: 104px;
  padding: 16px 24px;
  font-size: 14px;
  color: #323333;
  background: #fff;
  border-radius: 6px;
  box-shadow:
    0 6px 30px 5px rgb(0 0 0 / 5%),
    0 16px 24px 2px rgb(0 0 0 / 4%),
    0 8px 10px -5px rgb(0 0 0 / 8%);

  .header {
    display: flex;
    padding-bottom: 12px;

    .title {
      flex: 1;
      font-size: 16px;
      font-weight: 600;
      line-height: 22px;
    }

    .px-icon {
      font-size: 22px;
      color: #3b82f6;
      text-align: right;
    }
  }

  .footer {
    display: flex;

    > div {
      flex: 1;
    }

    .right {
      text-align: right;
    }

    .left {
      text-align: left;
    }
  }
}

:deep(.px-timeline-item) {
  padding-bottom: 50px;
}

:deep(.px-timeline-item__wrapper) {
  top: 0;
}

:deep(.px-timeline-item__node--normal) {
  top: -3px;
  left: -6px;
  width: 24px;
  height: 28px;

  &::before {
    width: 24px;
    height: 21px;
  }
}

:deep(.px-timeline-item__node) {
  border: none;
  border-radius: 0;

  &::before {
    border: none;
    border-radius: 0;
  }
}

:deep(.px-timeline-item .px-timeline-item__icon) {
  width: 24px;
  height: 21px;

  svg {
    width: 100%;
    height: 100%;
  }
}

:deep(.px-timeline-item__tail) {
  border-left: 1px solid #dcdcdc;
}

:deep(.px-timeline-item.stop .px-timeline-item__tail) {
  &::after {
    position: absolute;
    top: 50%;
    left: -5px;
    width: 10px;
    height: 10px;
    font-size: 12px;
    color: #dcdcdc;
    text-align: center;
    content: "X";
  }
}

:deep(.custom-form-ui .px-form-item) {
  margin-bottom: 0;
}

:deep(.px-radio__label) {
  display: none;
}

:deep(.px-radio:last-child) {
  margin-right: 32px;
}
</style>
